<template>
  <n-space vertical>
    <NRow>
      <h3>{{ domain?.zoneConfig?.origin }}</h3>
    </NRow>
    <n-row>
      <n-space>
        <NButton
          type="primary"
          @click="
            () => {
              action = Action.Add
              showAdd = true
            }
          "
        >
          <template #icon>
            <NIcon>
              <AddCircle></AddCircle>
            </NIcon> </template
          >添加</NButton
        >
        <NButton type="warning" @click="preview = true">
          <template #icon>
            <NIcon>
              <EllipsisHorizontalCircleSharp></EllipsisHorizontalCircleSharp>
            </NIcon>
          </template>
          preview zonefile</NButton
        >
      </n-space>
    </n-row>

    <NDataTable
      :single-line="false"
      :row-key="(row) => row.uuid"
      :columns="cols"
      :data="domain?.records"
      striped
      :pagination="{ pageSize: 10 }"
    >
    </NDataTable>
  </n-space>

  <NModal
    v-model:show="showAdd"
    preset="card"
    style="width: 600px"
    :title="action === Action.Add ? '添加解析' : '修改解析'"
    @after-leave="resetRecord"
  >
    <n-form>
      <n-form-item label="sub">
        <n-input-group>
          <n-input v-model:value="record.origin"></n-input>
          <NInputGroupLabel>{{ domain?.zoneConfig?.origin }}</NInputGroupLabel>
        </n-input-group>
      </n-form-item>
      <NFormItem label="ttl">
        <DurationInput
          v-model:value="record.ttl.value"
          v-model:unit="record.ttl.unit"
        ></DurationInput>
      </NFormItem>
      <NFormItem label="type">
        <NSelect v-model:value="record.type" :options="typeOptions"></NSelect>
      </NFormItem>
      <n-form-item label="data">
        <n-input v-model:value="record.data"></n-input>
      </n-form-item>
      <NFormItem label="comment">
        <n-input v-model:value="record.comment" type="textarea" placeholder="基本的 Textarea" />
      </NFormItem>
    </n-form>
    <template #footer>
      <n-space justify="end">
        <n-button @click="showAdd = false">取消</n-button>
        <n-button v-if="action === Action.Add" type="primary" @click="addRecord">添加</n-button>
        <n-button v-if="action === Action.Update" type="primary" @click="updateRecord"
          >更新</n-button
        >
      </n-space>
    </template>
  </NModal>

  <NModal title="preview" v-model:show="preview" preset="card" style="width: 750px">
    <NSwitch v-model:value="trimDur"></NSwitch>
    <NConfigProvider :hljs="hljs">
      <NCode :code="domain ? toZonefile(domain, trimDur) : ''" language="dns"></NCode>
    </NConfigProvider>
  </NModal>
</template>
<script setup lang="ts">
import {
  NButton,
  NModal,
  NRow,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NInputGroupLabel,
  NSpace,
  NDataTable,
  NSelect,
  NConfigProvider,
  NCode,
  NIcon,
  NSwitch
} from 'naive-ui'
import type { DataTableColumns, SelectOption } from 'naive-ui'
import { toZonefile } from '@/utils/zonefile'
import hljs from 'highlight.js/lib/core'
import hljsLangDns from 'highlight.js/lib/languages/dns'
import { cloneDeep } from 'lodash'
import { useDialog } from 'naive-ui'
import { AddCircle, EllipsisHorizontalCircleSharp, TrashBin } from '@vicons/ionicons5'
import { Edit24Filled } from '@vicons/fluent'
hljs.registerLanguage('dns', hljsLangDns)

const domain = ref<Domain | null>(null)
const route = useRoute()
const name = route.params.name
async function getDomainInfo() {
  const { data } = await useFetch<Domain>(`/api/domain/${name}`, {
    method: 'get'
  })
  domain.value = data.value
}
await getDomainInfo()

const trimDur = ref(false)

const typeOptions: SelectOption[] = [
  {
    label: 'A',
    value: 'A'
  },
  {
    label: 'AAAA',
    value: 'AAAA'
  },
  {
    label: 'TXT',
    value: 'TXT'
  },
  {
    label: 'CNAME',
    value: 'CNAME'
  }
]

const showAdd = ref(false)

const defaultRecord = (): RRecord => ({
  origin: '@',
  type: 'A',
  data: '',
  ttl: {
    value: 3600,
    unit: ''
  }
})
const record = ref<RRecord>(defaultRecord())

async function addRecord() {
  await useFetch(`/api/domain/${name}/record`, {
    method: 'POST',
    body: record.value,
    watch: false
  })
  showAdd.value = false
  getDomainInfo()
}
enum Action {
  Update,
  Add
}
// const updateShow = ref(false)
const action = ref(Action.Add)

async function updateRecord() {
  await useFetch(`/api/domain/${name}/record/${record.value.uuid}`, {
    method: 'PATCH',
    body: record.value,
    watch: false
  })
  showAdd.value = false
  getDomainInfo()
}
const dialog = useDialog()
function deleteConfirm(row: RRecord) {
  dialog.warning({
    title: '警告',
    content: '你确定？',
    positiveText: '确定',
    negativeText: '不确定',
    onPositiveClick: () => {
      deleteRecord(row.uuid || '')
    },
    onNegativeClick: () => {
      // message.error('不确定')
    }
  })
}

async function deleteRecord(id: string) {
  await useFetch(`/api/domain/${name}/record/${id}`, {
    method: 'DELETE',
    watch: false
  })
  getDomainInfo()
}

function resetRecord() {
  record.value = defaultRecord()
}

const cols: DataTableColumns<RRecord> = [
  {
    type: 'selection'
  },
  {
    title: 'ns',
    key: 'origin',
    sorter: 'default'
  },
  { title: 'type', key: 'type' },
  {
    title: 'ttl',
    key: 'ttl',
    render(row) {
      return row.ttl.value + (row.ttl.unit || '')
    }
  },
  {
    title: 'rd',
    key: 'data'
  },
  {
    title: 'comment',
    key: 'comment'
  },
  {
    title: 'op',
    key: 'op',
    width: '250px',
    render(row) {
      return h(
        NSpace,
        { justify: 'space-around' },
        {
          default: () => [
            h(
              NButton,
              {
                type: 'info',
                size: 'small',
                onClick: () => {
                  record.value = cloneDeep(row)
                  action.value = Action.Update
                  showAdd.value = true
                }
              },
              {
                icon: () => h(NIcon, {}, { default: () => h(Edit24Filled) }),
                default: () => 'edit'
              }
            ),
            h(
              NButton,
              {
                type: 'error',
                size: 'small',
                onClick: () => {
                  deleteConfirm(row)
                }
              },
              { icon: () => h(NIcon, {}, { default: () => h(TrashBin) }), default: () => 'delete' }
            )
          ]
        }
      )
    }
  }
]

const preview = ref(false)
</script>
<script lang="ts">
export default {
  name: 'DomainDetail'
}
</script>
